import * as XLSX from "xlsx";
const wbOption = {
  bookType: "xlsx",
  bookSST: false,
  type: "binary",
};

// 1.導出非文件流格式的excel
export default (data, sheetName = "sheet1", fileName = "json2Excel.xlsx") => {
  const jsonWorkSheet = XLSX.utils.json_to_sheet(data);
  const workBook = {
    SheetNames: [sheetName], // 指定有序 sheet 的 name
    Sheets: {
      [sheetName]: jsonWorkSheet, // 表格数据内容
      // [sheetName]: data, // 表格数据内容
    },
  };

  return XLSX.writeFile(workBook, fileName); // 向文件系统写出文件
};

// 2.导出文件流格式的excel， 在需要用到的地方得到返回值配合FileSaver.saveAs做导出
export const exportOfBlob = ({
  jsonData,
  excelKeyToName, // 数据的映射：excel表头
  sheetName = "sheet1",
  fileName = "json2Excel.xlsx",
  wbOptionObj = wbOption,
}) => {
  // 格式化参数
  const data = jsonData.map((item) => {
    const newItem = {};
    Object.keys(item).forEach((key) => {
      newItem[excelKeyToName[key]] = item[key];
    });
    return newItem;
  });
  const jsonWorkSheet = XLSX.utils.json_to_sheet(data);

  const workBook = {
    SheetNames: [sheetName], // 指定有序 sheet 的 name
    Sheets: {
      [sheetName]: jsonWorkSheet, // 表格数据内容
    },
  };
  return XLSX.write(workBook, wbOptionObj);
};

export function s2ab(s) {
  if (typeof ArrayBuffer !== "undefined") {
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  } else {
    let buf = new Array(s.length);
    for (let i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
}
